package com.sjq.common.service.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sjq.common.dao.MenuTreeDao;
import com.sjq.common.entity.MenuTree;
import com.sjq.common.exception.DataAccessException;
import com.sjq.common.exception.ServiceException;
import com.sjq.common.service.MenuTreeService;

@Service
public class MenuTreeServiceImpl implements MenuTreeService{

	@Autowired
	private MenuTreeDao menuTreeDao;
	
	@Override
	public List<Map<String, Object>> findAllJsTree() throws ServiceException {
		List<Map<String, Object>> allMenu=menuTreeDao.selectAllJsTree();
		return allMenu;
	}


	@Override
	public MenuTree findSingleJsTree(String pid) throws ServiceException {
		MenuTree jsTree=menuTreeDao.selectSingleJsTree(pid);
		return jsTree;
	}

	@Override
	public List<Map<String, Object>> findJsTreeChildren() throws ServiceException {
		List<Map<String, Object>> jsTreeChildren = menuTreeDao
				.selectJsTreeChildren();
		return jsTreeChildren;
	}


	@Override
	public MenuTree findSingleMenu(String menuId) throws ServiceException {
		MenuTree menu=menuTreeDao.selectSingleMenu(menuId);
		return menu;
	}

	@Override
	public void addMenu(MenuTree menu) throws ServiceException {
		if(menu==null){
			return;
		}
		menuTreeDao.insertMenu(menu);
	}

	@Override
	public void modifyMenu(MenuTree menu) throws ServiceException {
		if (menu == null) {
			return;
		}
		menuTreeDao.updateMenu(menu);
	}

	@Override
	public void removePrivilege(String menuId) throws ServiceException {
		menuTreeDao.deletePrivilege(menuId);
	}

	@Override
	public void removePermission(String menuId) throws ServiceException {
		if (menuId == null || menuId.trim() == "") {
			return;
		}
		menuTreeDao.deletePermission(menuId);
	}

	@Override
	public void removeMenu(String menuId) throws ServiceException {
		if (menuId == null || menuId.trim() == "") {
			return;
		}
		menuTreeDao.deleteMenu(menuId);
	}

	@Override
	public List<Map<String, Object>> findMenuNameByPid(String pid) throws DataAccessException {
		List<Map<String, Object>> list=menuTreeDao.selectMenuNameByPid(pid);
		return list;
	}

	/***更新权限组的授权**/
	@Override
	public void updatePrivilege(String nodeArray, String authorityId)
			throws ServiceException {
		menuTreeDao.deleteAuthoriedMenu(authorityId);
		String  []a =nodeArray.split(",");
		for(int i=0;i<a.length;i++){
			menuTreeDao.insertAuthoriedMenu(a[i], authorityId);
		}
	}


	@Override
	public List<Map<String, String>> queryMenusByAuthority(String authorityId) {
		List<Map<String, String>> res=null;
		try {
			res=	menuTreeDao.findAuthoriedMenu(authorityId);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return res;
	}

}
